package com.atguigu.datastream.test.day01;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * ClassName: Flink02_Stream_WordCount_Bounded
 * Package: com.atguigu.test
 * Description:
 *
 * @Author ChenJun
 * @Create 2023/4/6 21:18
 * @Version 1.0
 */
public class Flink02_Stream_WordCount_Bounded {
    public static void main(String[] args) throws Exception {

        //1. 创建 flink 流处理运行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //设置并行度
        env.setParallelism(1);

        //2.读取文件
        DataStreamSource<String> streamSource = env.readTextFile("input/word.txt");

        //3. 将文件按照空格切分为一个一个的单词
        SingleOutputStreamOperator<Tuple2<String, Long>> wordToOne = streamSource.flatMap(new FlatMapFunction<String, Tuple2<String, Long>>() {
            @Override
            public void flatMap(String s, Collector<Tuple2<String, Long>> collector) throws Exception {
                String[] words = s.split(" ");
                for (String word : words) {
                    collector.collect(Tuple2.of(word, 1L));
                }
            }
        });

        //4. 按照单词进行分组
        KeyedStream<Tuple2<String, Long>, Tuple> keyedStream = wordToOne.keyBy("f0");

        //5. 进行sum 计算
        SingleOutputStreamOperator<Tuple2<String, Long>> result = keyedStream.sum("f1");

        //6. 打印输出
        result.print();

        //7. 执行
        env.execute();
    }
}
